// -*- coding: utf-8 -*-
/*
author: zengbin93
email: zeng_bin8888@163.com
create_dt: 2022/12/16 19:42
describe: 飞书电子表格相关功能
*/

use crate::fsa::base::{request, FeishuApiBase};
use loguru::logger;
use serde_json::Value;
use std::collections::HashMap;

/// 飞书电子表格类
pub struct SpreadSheets {
    base: FeishuApiBase,
}

impl SpreadSheets {
    pub fn new(app_id: &str, app_secret: &str) -> Self {
        Self {
            base: FeishuApiBase::new(app_id, app_secret),
        }
    }
    
    /// 获取电子表格中的所有工作表
    pub async fn get_sheets(&mut self, spreadsheet_token: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/sheets/query", spreadsheet_token);
        let headers = self.base.get_headers().await?;
        request("GET", &url, &headers, None).await
    }
    
    /// 读取表格数据
    pub async fn read_table(&mut self, spreadsheet_token: &str, sheet_id: &str) -> Result<Vec<HashMap<String, String>>, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values/{}", spreadsheet_token, sheet_id);
        let headers = self.base.get_headers().await?;
        let resp = request("GET", &url, &headers, None).await?;
        
        let values = resp["data"]["valueRange"]["values"].as_array().unwrap();
        if values.is_empty() {
            return Ok(vec![]);
        }
        
        let headers_row = values[0].as_array().unwrap();
        let headers: Vec<String> = headers_row
            .iter()
            .map(|v| v.as_str().unwrap_or("").to_string())
            .collect();
        
        let mut result = Vec::new();
        for row in values.iter().skip(1) {
            let row_data = row.as_array().unwrap();
            let mut row_map = HashMap::new();
            
            for (i, cell) in row_data.iter().enumerate() {
                if i < headers.len() {
                    let value = cell.as_str().unwrap_or("").to_string();
                    row_map.insert(headers[i].clone(), value);
                }
            }
            
            result.push(row_map);
        }
        
        Ok(result)
    }
    
    /// 删除表格数据
    pub async fn delete_values(&mut self, spreadsheet_token: &str, sheet_id: &str) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values/{}", spreadsheet_token, sheet_id);
        let headers = self.base.get_headers().await?;
        request("DELETE", &url, &headers, None).await
    }
    
    /// 更新表格数据
    pub async fn update_values(&mut self, spreadsheet_token: &str, data: &Value) -> Result<Value, Box<dyn std::error::Error>> {
        let url = format!("https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/{}/values/batchUpdate", spreadsheet_token);
        let headers = self.base.get_headers().await?;
        request("POST", &url, &headers, Some(data)).await
    }
}

/// 单个工作表类
pub struct SingleSheet {
    spreadsheet_token: String,
    sheet_id: String,
    base: FeishuApiBase,
}

impl SingleSheet {
    pub fn new(spreadsheet_token: &str, sheet_id: &str, app_id: &str, app_secret: &str) -> Self {
        Self {
            spreadsheet_token: spreadsheet_token.to_string(),
            sheet_id: sheet_id.to_string(),
            base: FeishuApiBase::new(app_id, app_secret),
        }
    }
    
    /// 读取工作表数据
    pub async fn read(&mut self) -> Result<Vec<HashMap<String, String>>, Box<dyn std::error::Error>> {
        let mut ss = SpreadSheets::new(&self.base.app_id, &self.base.app_secret);
        ss.read_table(&self.spreadsheet_token, &self.sheet_id).await
    }
    
    /// 写入工作表数据
    pub async fn write(&mut self, data: &[HashMap<String, String>]) -> Result<Value, Box<dyn std::error::Error>> {
        if data.is_empty() {
            return Ok(serde_json::json!({}));
        }
        
        let headers: Vec<String> = data[0].keys().cloned().collect();
        let values: Vec<Vec<String>> = data
            .iter()
            .map(|row| headers.iter().map(|key| row.get(key).unwrap_or(&String::new()).clone()).collect())
            .collect();
        
        let update_data = serde_json::json!({
            "valueRanges": [
                {
                    "range": format!("{}!A1:Z1", self.sheet_id),
                    "values": [headers]
                },
                {
                    "range": format!("{}!A2:Z5000", self.sheet_id),
                    "values": values
                }
            ]
        });
        
        let mut ss = SpreadSheets::new(&self.base.app_id, &self.base.app_secret);
        ss.update_values(&self.spreadsheet_token, &update_data).await
    }
    
    /// 清空工作表数据
    pub async fn clear(&mut self) -> Result<Value, Box<dyn std::error::Error>> {
        let mut ss = SpreadSheets::new(&self.base.app_id, &self.base.app_secret);
        ss.delete_values(&self.spreadsheet_token, &self.sheet_id).await
    }
} 